package resolver

import (
	"crypto/md5"
	"crypto/sha1"
	"crypto/sha512"
	"fmt"
	"hash"
	"io"
	"os"
	"strings"
)

type FileInfo struct {
	Path          string
	name          string
	size          int64
	IsDir         bool
	Hash          string
	hashAlgorithm hash.Hash
	OptType       int // 0：add, 1：nomal, 2：update, 3：delete
}

func NewFileInfo(path, name string, IsDir bool, size int64, algorithmType AlgorithmType) *FileInfo {
	var hashAlgorithm hash.Hash
	if algorithmType == Md5 {
		hashAlgorithm = md5.New()
	} else if algorithmType == Sha1 {
		hashAlgorithm = sha1.New()
	} else if algorithmType == Sha512 {
		hashAlgorithm = sha512.New()
	}
	path = strings.Trim(path, "")
	return &FileInfo{Path: path, name: name, IsDir: IsDir, size: size, hashAlgorithm: hashAlgorithm}
}

func (fi *FileInfo) ToString() string {
	msg := ""
	if fi.IsDir {
		msg += "目录："
	} else {
		msg += "文件："
	}
	msg += fi.Path
	return msg
}

func (fi *FileInfo) ToAllString() string {
	var isDir int
	if fi.IsDir {
		isDir = 1
	}
	msg := fmt.Sprintf("%v%s%v%s%v%s%v%s%v", fi.Path, Split, fi.name, Split, isDir, Split, fi.size, Split, fi.Hash)
	return msg
}

func (fi *FileInfo) write(d interface{}) {
	var r io.Reader
	var err error
	switch d.(type) {
	case string:
		r, err = os.Open(d.(string))
		if err != nil {
			fmt.Println(err)
			return
		}
	case io.Reader:
		r = d.(io.Reader)
	}
	if r != nil {
		readBytes := make([]byte, 1024*10)
		for {
			n, err := r.Read(readBytes)
			if err == io.EOF {
				break
			}
			if err != nil {
				fmt.Println(err)
				return
			}
			fi.hashAlgorithm.Write(readBytes[:n])
		}
		// 计算Hash值
		fi.Hash = fmt.Sprintf("%x", (fi.hashAlgorithm.Sum(nil)))
	}
}
